package com.tangula.web.kashine.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.nimbusds.oauth2.sdk.util.StringUtils;
import com.tangula.core.Context;
import com.tangula.web.config.auth.Ignore;

@Controller
@RequestMapping("/viewImageController")
public class ViewImageController implements com.tangula.core.Controller<Context>, AuthController {

	public static final String KASHINE_IMAGE = "kashine_image";

	
	@RequestMapping(value = "/view/{imageId}", produces = MediaType.IMAGE_PNG_VALUE, method = { RequestMethod.GET })
	@Ignore
	public void view(@PathVariable("imageId") String imageId, HttpServletResponse resp) {
		if (StringUtils.isNotBlank(imageId)) {
			logDebug("view image id is "+imageId);
			String home = System.getProperty("user.home");

			File parent_file = new File(home, KASHINE_IMAGE);

			if (parent_file.exists()) {

				File image_file = new File(parent_file, imageId);

				if (image_file.exists()) {
					try (FileInputStream fos = new FileInputStream(image_file)) {

						byte[] buf = new byte[5120];
						int len = 0;

						OutputStream os = null;
						try {
							os = resp.getOutputStream();
							while ((len = fos.read(buf)) >= 0) {
								os.write(buf, 0, len);
							}
							os.flush();
						} catch (IOException e) {
							logError(e);
						}
					} catch (FileNotFoundException e) {
						logError(e);
					} catch (IOException e) {
						logError(e);
					}
				}else {
					logInfo("image file not exist:"+image_file.getPath());
				}

			}else {
				logInfo("image parent file not exist:"+parent_file.getPath());
			}
		}else {
			logDebug("view image id is blank");
		}
	}
	
}
